﻿//用MSWord替代过长的引用类型
using MSWord = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;

namespace OperateExcelInWord
{
    internal class Program
    {
        static void Main(string[] args)
        {

            for(int i=1;i<2;i++)
            {
                Object Nothing = System.Reflection.Missing.Value;
                string path = Environment.CurrentDirectory + $"\\test{i}.docx";
                object file = path;
                MSWord.Application wordApp = new MSWord.Application();
                MSWord.Document wordDoc = wordApp.Documents.Open(file);//(带占位符的模板文件名);
                wordApp.Visible = true;
                wordDoc.Activate();
                for(int j=1;j<9;j++)
                {
                    FindAndReplace(wordApp, $"@@{j}", "分数");
                }
                
                object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;
                wordDoc.SaveAs(ref file, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            }
            
            Console.WriteLine("Finished！");


        }

        //函数，用于交换内容
        private static void FindAndReplace(Microsoft.Office.Interop.Word.Application WordApp, object findText, object replaceWithText)
        {
            object matchCase = true; 
            object matchWholeWord = false; 
            object matchWildCards = false;
            object matchSoundsLike = false;
            object nmatchAllWordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object read_only = false;
            object visible = true;
            object replace = 2;
            object wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
            object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
            WordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike,
            ref nmatchAllWordForms, ref forward,
            ref wrap, ref format, ref replaceWithText,
            ref replaceAll, ref matchKashida,
            ref matchDiacritics, ref matchAlefHamza,
            ref matchControl);
        }

    }
}